package com.second.hand.trading.server.controller;

import com.second.hand.trading.server.domain.User;
import com.second.hand.trading.server.service.UserDemoService;
import com.second.hand.trading.server.service.UserService;
import com.second.hand.trading.server.utils.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
public class UserDemoController {

    private final UserDemoService userService;
    private final HttpSession session;

    public UserDemoController(UserDemoService userService, HttpSession session) {
        this.userService = userService;
        this.session = session;
    }

    @PostMapping("/doLogin")
    public R<String> doLogin(String accountNumber, String userPassword) {
        if (accountNumber == null || "".equals(accountNumber)) {
            return R.fail("用户名不能为空");
        }
        if (userPassword == null || "".equals(userPassword)) {
            return R.fail("密码不能为空");
        }
        User user = userService.selectByAccountNumber(accountNumber);
        if (user == null) {
            return R.fail("用户名错误");
        }
        if (!user.getUserPassword().equals(userPassword)) {
            return R.fail("密码错误");
        }
        String token = UUID.randomUUID().toString();
        session.setAttribute(token, user);
        return R.success(token);
    }

    @PostMapping("/doLogout")
    public R<?> doLogout(@RequestHeader("token") String token) {
        session.removeAttribute(token);
        return R.success();
    }
}
